<script setup lang="ts">
  import commissionIcon from '/images/webp/affiliate-program/commission-icon.webp'
  import commissionDetailIcon from '/images/webp/affiliate-program/commissionDetailIcon.webp'
  import commissionRecordIcon from '/images/webp/affiliate-program/commissionRecordIcon.webp'
  import directCommissionImg from '/images/webp/affiliate-program/direct-commission-img.webp'
  import faqIcon from '/images/webp/affiliate-program/faqIcon.webp'
  import financeDataIcon from '/images/webp/affiliate-program/financeData.webp'
  import link from '/images/webp/affiliate-program/link.webp'
  import linkActive from '/images/webp/affiliate-program/link_active.webp'
  import medal from '/images/webp/affiliate-program/medal.webp'
  import myDataImg from '/images/webp/affiliate-program/my-data-img.webp'
  import myDataIcon from '/images/webp/affiliate-program/myDataIcon.webp'
  import ratio from '/images/webp/affiliate-program/ratio.webp'
  import ratioActive from '/images/webp/affiliate-program/ratio_active.webp'
  import teamCommissionImg from '/images/webp/affiliate-program/team-commission-img.webp'
  import usdtImg from '/images/webp/statistics/usdt.webp'
  import BaseCurrencyIcon from '~/components/BaseCurrencyIcon.vue'
  import BaseImage from '~/components/BaseImage.vue'
  import BaseTable from '~/components/BaseTable.vue'
  import { ApiAgencyCommissionBalance } from '~/apis'
  const {  t  } = useI18n()
  const appStore = useAppStore()
  const tab = ref('')
  const tab2 = ref('')
  const tabList = ref<{ label: string; value: string; icon: string }[]>([])
  const { userLanguage } = storeToRefs(useLanguageStore())
  // const { openNotify } = useNotify()
  const { bonus_currency, bonus_limit ,link_url ,rules ,cond_direct,cond_team} = storeToRefs(useAffiliate())
  const location = useBrowserLocation()
  definePageMeta({
    layout: 'header-back',
    title: 'affiliate_program'
  })

  const {
    data: balanceAgency,
    runAsync: getBalanceAgency,
  } = useRequest(ApiAgencyCommissionBalance)

  const {
    run: runTransferToMember,
    loading: loadTransferToMember,
  } = useRequest(ApiAgencyTransferToMember, {
    onSuccess() {
      // openNotify({
      //   type:'success',
      //   title: t('finance_funds_transfer_commission_withdraw'),
      //   icon: 'navbar-wallet-notify',
      //   message: t('commission_draw_success'),
      // })
      appStore.getBalanceData()
      getBalanceAgency()
    },
  })

  const {
    data: modelsList,
    runAsync: runAsyncModelsList,
  } = useRequest(ApiAgencyCommissionModelsList, {
    onSuccess(data) {
      console.log('data', data)
      if (data)
        tab.value = data[0].id
      tab2.value = data[0].id
    },
  })


  const agencyInfo = computed(() => {
    if (!balanceAgency.value)
      return '0.00'
    const current_bonus = balanceAgency.value.balance

    // 大于上限使用上限 0或空 无上限
    if (!(Number(bonus_limit.value) == 0 || !bonus_limit.value) && Number(current_bonus) > Number(bonus_limit.value))
      return bonus_limit.value
    else
      return current_bonus
  })

  const qrUrl = computed(() => `${location.value.origin}${link_url.value ?? ''}`)

  const contents = computed(() => {
    return rules.value[EnumLanguage[userLanguage.value]]
  })

  const directColumns = ref([
    {
      title: t('affiliate_program_level'),
      dataIndex: 'lvl',
      slot: 'lvl',
      align: 'center'
    },
    {
      title: t('affiliate_program_valid_bet'),
      dataIndex: 'amt',
      slot: 'amt',
      align: 'center'
    },
    {
      title: t('affiliate_program_commission_ratio'),
      dataIndex: 'rate',
      slot: 'rate',
      align: 'center'
    }

  ])

  function copyLink() {
    // 复制链接实现
  }

  const activeTab = ref('invite') // 'invite' 或 'commission'

  function switchTab(tab: string) {
    activeTab.value = tab
  }

  const dataListDirect = computed(() => {
    const currentSelected = tab.value
    let selectData = cond_direct.value ? JSON.parse(cond_direct.value) : []
    const result = selectData.reduce((acc, cur) => {
      const { lvl, ty } = cur
      // const modelIds = model_ids.split(',')
      if (ty === currentSelected && Array.isArray(lvl))
        acc.push(...lvl)
      return acc
    }, [] as any[])

    return result
  })
  const dataListTeam = computed(() => {
    const currentSelected = tab2.value
    let selectData = cond_team.value ? JSON.parse(cond_team.value) : []
    const result = selectData.reduce((acc, cur) => {
      const { lvl, ty } = cur
      // const modelIds = model_ids.split(',')
      if (ty === currentSelected && Array.isArray(lvl))
        acc.push(...lvl)
      return acc
    }, [] as any[])

    return result
  })


  function navigateTo(path: string) {
    i18nNavigateTo(`/affiliate-program/${path}`)
  }

  function changeTab(type:string,item){
    if(type == '2'){
      tab2.value = item.value
    }else{
      tab.value = item.value
    }
  }


  async function getData() {
    return new Promise(async (resolve) => {
      await runAsyncModelsList()
      ApiAgencyCommissionScale().then((res) => {
        tabList.value = modelsList.value!.map((a, i) => {
          return {
            label: a.name,
            value: a.id,
            icon: res.conf[i].ico[0],
            useCloudImg: true,
          }
        })
        console.log(tabList,'tabList')
        resolve(true)
      }).catch(() => {
        console.error('error')
        resolve(false)
      })
    })
  }

  onMounted(async () => {
    appStore.updateUserInfo()
    await application.allSettled(
      [
        getBalanceAgency(),
        getData()
      ],
    )
  })
</script>

<template>
  <div class="affiliate-container" :key="bonus_currency">
    <!-- 用户信息 -->
    <div class="user-info-card">
      <div class="user-id">
        <span class="name-title">{{ t('affiliate_program_account') }}：</span>
        <span class="id-value">{{balanceAgency?.username}}</span>
      </div>
      <div class="flex justify-center items-center mb-2 card-icons">
        <BaseImage width="32px" :url="commissionIcon" class="img"/>
      </div>
      <div class="commission">
        <div class="available-text">{{ t('affiliate_program_available_commission') }}：</div>
        <div class="amount">{{ agencyInfo }}</div>
        <!--        <BaseCurrencyIcon style="width: 14px; height: 14px" :cur="getCurrencyConfigByCode(bonus_currency)?.name" />-->
        <BaseImage width="14px" :url="usdtImg" class="img"/>
      </div>
      <BaseButton  :disabled="Number(agencyInfo) <= 0"  :loading="loadTransferToMember"  @click="runTransferToMember" class="withdraw-btn">
        {{ t('affiliate_program_withdraw_commission') }}
      </BaseButton>
    </div>

    <!-- 功能导航 -->
    <div class="function-nav">
      <div class="nav-item" @click="navigateTo('my-data')">
        <div class="w-[24px] h-[24px] flex items-center justify-center">
          <BaseImage fit="cover" width="12px" heigth="16px" :url="myDataIcon" />
        </div>
        <div class="nav-text">
          {{ t('affiliate_program_my_data') }}
        </div>
      </div>
      <div class="nav-item" @click="navigateTo('finance-data')">
        <div class="w-[24px] h-[24px] flex items-center justify-center">
          <BaseImage fit="cover" width="12px" heigth="16px" :url="financeDataIcon" />
        </div>
        <div class="nav-text">
          {{ t('affiliate_program_finance_data') }}
        </div>
      </div>
      <div class="nav-item" @click="navigateTo('commission-record')">
        <div class="w-[24px] h-[24px] flex items-center justify-center">
          <BaseImage width="26px" heigth="26px" :url="commissionRecordIcon" />
        </div>
        <div class="nav-text">
          {{ t('affiliate_program_commission_record') }}
        </div>
      </div>
      <div class="nav-item" @click="navigateTo('commission-detail')">
        <div class="w-[24px] h-[24px] flex items-center justify-center">
          <BaseImage width="14px" heigth="16px" :url="commissionDetailIcon" />
        </div>
        <div class="nav-text">
          {{ t('affiliate_program_commission_detail') }}
        </div>
      </div>
      <div class="nav-item" @click="navigateTo('faq')">
        <div class="w-[24px] h-[24px] flex items-center justify-center">
          <BaseImage width="16px" heigth="18px" :url="faqIcon" />
        </div>
        <div class="nav-text">
          {{ t('affiliate_program_faq') }}
        </div>
      </div>
    </div>

    <!-- 邀请链接导航栏 -->
    <div class="invite-link-tabs">
      <div class="tab" :class="{ active: activeTab === 'invite' }" @click="switchTab('invite')">
        <div class="tab-icon">
          <BaseImage width="24px" :url="activeTab === 'invite' ? linkActive : link" />
        </div>
        <div class="tab-text">
          {{ t('affiliate_program_invite_link') }}
        </div>
      </div>
      <div
        class="tab"
        :class="{ active: activeTab === 'commission' }"
        @click="switchTab('commission')"
      >
        <div class="tab-icon">
          <BaseImage width="24px" :url="activeTab === 'commission' ? ratioActive : ratio" />
        </div>
        <div class="tab-text">
          {{ t('affiliate_program_commission_ratio') }}
        </div>
      </div>
    </div>

    <!-- 邀请链接内容 -->
    <template v-if="activeTab === 'invite'">
      <!-- 邀请朋友 -->
      <div class="invite-section">
        <div class="invite-header">
          <div class="text">
            {{ t('affiliate_program_invite_friends') }}
          </div>
        </div>
        <div class="copy-section">
          <div class="invite-desc">
            {{ t('affiliate_program_commission_description') }}
            <br />
            {{ t('affiliate_program_commission_calculation') }}
          </div>
          <div class="link-container">
            <div class="link-text">
              {{ t('affiliate_program_referral_link') }}
            </div>
            <div class="link-box">
              <span class="link-url">{{ qrUrl }}</span>
              <button class="copy-btn" @click="copyLink">
                {{ t('affiliate_program_copy') }}
              </button>
            </div>
          </div>
        </div>

        <!-- 社交分享 -->
        <div class="social-share">
          <div class="share-title">
            {{ t('affiliate_program_share_social') }}
          </div>
          <div class="social-icons">
            <div class="social-item">
              <div class="icon facebook">
                <i class="fab fa-facebook-f" />
              </div>
              <div class="icon-text">FACBOOK</div>
            </div>
            <div class="social-item">
              <div class="icon telegram">
                <i class="fab fa-telegram-plane" />
              </div>
              <div class="icon-text">Telegram</div>
            </div>
            <div class="social-item">
              <div class="icon instagram">
                <i class="fab fa-instagram" />
              </div>
              <div class="icon-text">Instagram</div>
            </div>
            <div class="social-item">
              <div class="icon youtube">
                <i class="fab fa-youtube" />
              </div>
              <div class="icon-text">YouTube</div>
            </div>
            <div class="social-item">
              <div class="icon whatsapp">
                <i class="fab fa-whatsapp" />
              </div>
              <div class="icon-text">WhatsApp</div>
            </div>
            <div class="social-item">
              <div class="icon x">
                <i class="fab fa-x-twitter" />
              </div>
              <div class="icon-text">X</div>
            </div>
            <div class="social-item">
              <div class="icon line">
                <i class="fab fa-line" />
              </div>
              <div class="icon-text">LINE</div>
            </div>
            <div class="social-item">
              <div class="icon tiktok">
                <i class="fab fa-tiktok" />
              </div>
              <div class="icon-text">TikTok</div>
            </div>
            <div class="social-item">
              <div class="icon gmail">
                <i class="far fa-envelope" />
              </div>
              <div class="icon-text">Gmail</div>
            </div>
          </div>
        </div>
        <div class="support-text">
          {{ t('affiliate_program_referral_conditions') }}
        </div>
      </div>

      <!-- 用户层级关系图 -->
      <div class="hierarchy-chart">
        <BaseImage class="w-full h-full" :url="myDataImg" />
      </div>

      <!-- 规则说明 -->
      <div class="rules-section">
        <div class="rule-title">
          {{ t('affiliate_program_rules_explanation') }}
        </div>
        <div class="rule-content">
          <div v-for="(item, index) in contents" :key="index" class="flex items-baseline">
            <div>
              <div class="p">
                <div class="content" v-html="item.replace(/\n/g, '<br>')" />
              </div>
            </div>
          </div>
        </div>
      </div>
    </template>

    <!-- 返佣比例内容 -->
    <template v-else>
      <!-- 直属佣金 -->
      <div class="commission-table-section">
        <div class="section-title">
          <div class="title-text">
            {{ t('affiliate_program_direct_commission') }}
          </div>
          <BaseImage :url="directCommissionImg" />
        </div>

        <div class="game-tabs">
          <div class="game-tab" @click="changeTab('',item)" :class="{active:tab == item.value}" v-for="(item,index) in tabList" :key="index">
            {{ item.label }}
          </div>
        </div>

        <BaseTable :columns="directColumns" :data-source="dataListDirect"  style="font-size: 12px">
          <template #lvl="{ record }">
            <div class="level-cell">
              <BaseImage width="14px" height="16px" :url="medal" />
              <span>{{ record.lvl }}</span>
            </div>
          </template>
          <template #amt="{ record }">
            <div class="price-cell">
              <span>{{ Number(record.amt).toFixed(2) }}+</span>
              <BaseCurrencyIcon style="transform: translateY(-1px)" :cur="getCurrencyConfigByCode(bonus_currency)?.name" />
            </div>
          </template>
        </BaseTable>
      </div>

      <!-- 团队佣金 -->
      <div class="commission-table-section">
        <div class="section-title">
          <div class="title-text">
            {{ t('affiliate_program_team_commission') }}
          </div>
          <BaseImage style="width: 64px" :url="teamCommissionImg" />
        </div>

        <div class="game-tabs">
          <div class="game-tab" @click="changeTab('2',item)" :class="{active:tab2 == item.value}" v-for="(item,index) in tabList" :key="index">
            {{ item.label }}
          </div>
        </div>

        <BaseTable :columns="directColumns" :data-source="dataListTeam" style="font-size: 12px">
          <template #lvl="{ record }">
            <div class="level-cell">
              <BaseImage width="14px" height="16px" :url="medal" />
              <span>{{ record.lvl }}</span>
            </div>
          </template>
          <template #amt="{ record }">
            <div class="price-cell">
              <span>{{ Number(record.amt).toFixed(2)  }}+</span>
              <BaseCurrencyIcon style="transform: translateY(-1px)" :cur="getCurrencyConfigByCode(bonus_currency)?.name" />
            </div>
          </template>
        </BaseTable>
      </div>
    </template>
  </div>
</template>

<style scoped lang="scss">
  .affiliate-container {
    background-color: #232626;
    color: white;
    min-height: 100vh;
    padding-bottom: 20px;
    display: flex;
    flex-direction: column;
    gap: 8px;
    margin: 16px;
    //overflow-y: scroll;
  }

  .user-info-card {
    position: relative;
    background-color: #323738;
    border-radius: 8px;
    padding: 8px;
    .user-id {
      z-index: 2;
      font-size: 10px;
      margin: 6px 0 0 6px;
      padding: 4px 10px;
      background-color: #464f50;
      border-radius: 4px;
      display: inline-block;
      font-weight: bold;
      .name-title{
        color: #B3BEC1;
      }
      .id-value {
        color: #4cd964;
      }
    }
    .card-icons{
      position:absolute;
      width: 100%;
      left: 0;
      top: 16px;
    }

    .commission {
      padding-top: 10px;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 10px;
      font-weight: bold;

      .available-text {
        font-size: 12px;
      }

      .amount {
        font-size: 14px;
        color: #4cd964;
        margin: 0 5px;
      }

      .icon-currency {
        color: #4cd964;
      }
    }

    .withdraw-btn {
      background: linear-gradient(90deg, #24ee89 0%, #9fe871 100%);
      color: #171a1a;
      border: none;
      border-radius: 6.98px;
      padding: 9.5px 12px;
      font-size: 14px;
      font-weight: bold;
      width: 100%;
    }
  }

  .function-nav {
    background-color: #3a4142;
    border-radius: 8px;
    padding: 16px;
    display: flex;
    justify-content: center;
    gap: 4px;

    .nav-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      row-gap: 3px;
      padding: 8px;

      .nav-icon {
        width: 24px;
        height: 24px;
        margin-bottom: 5px;
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .nav-text {
        font-size: 12px;
        color: #aaa;
      }
    }
  }

  .invite-link-tabs {
    display: flex;
    padding: 6px 8px;
    background-color: #323738;
    border-radius: 4px;

    .tab {
      flex: 1;
      text-align: center;
      padding: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      border-radius: 4px;
      color: #b3bec1;

      &:first-child {
        border-top-left-radius: 8px;
        border-bottom-left-radius: 8px;
      }

      &:last-child {
        border-top-right-radius: 8px;
        border-bottom-right-radius: 8px;
      }

      &.active {
        background-color: #3a4142;
        color: #fff;
      }

      .tab-icon {
        margin-right: 5px;

        i {
          font-size: 16px;
          color: #4cd964;
        }
      }

      .tab-text {
        font-size: 14px;
      }
    }
  }

  .invite-section {
    background-color: #323738;
    border-radius: 8px;
    padding: 16px;
    color: #b3bec1;
    font-weight: 600;

    .invite-header {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .link-icon {
        width: 24px;
        height: 24px;
        background-color: #4cd964;
        border-radius: 50%;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 10px;
      }

      .text {
        font-size: 16px;
      }
    }

    .divider {
      height: 1px;
      background-color: #444;
      margin: 10px 0;
    }

    .invite-desc {
      font-size: 12px;
      color: #b3bec1;
      line-height: 1.4;
      margin: 15px 0;
    }

    .link-container {
      margin-top: 20px;

      .link-text {
        font-size: 12px;
        margin-bottom: 5px;
        color: #b3bec1;
      }

      .link-box {
        display: flex;
        background-color: #3a4142;
        border-radius: 4px;
        padding: 4px;

        .link-url {
          flex: 1;
          display: flex;
          align-items: center;
          font-size: 12px;
          white-space: nowrap;
          overflow: hidden;
          text-overflow: ellipsis;
          color: #fff;
        }

        .copy-btn {
          background-color: #4a5354;
          color: white;
          font-size: 12px;
          font-weight: 700;
          border-radius: 4px;
          padding: 3px 12px;
        }
      }
    }

    .social-share {
      margin-top: 20px;

      .share-title {
        font-size: 14px;
        text-align: center;
        margin-bottom: 15px;
        color: #fff;
      }

      .social-icons {
        display: flex;
        flex-wrap: wrap;
        column-gap: 10px;
        row-gap: 15px;

        .social-item {
          display: flex;
          flex-direction: column;
          align-items: center;
          width: 60px;

          .icon {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 5px;

            i {
              font-size: 18px;
            }
          }

          .icon-text {
            font-size: 10px;
            color: #b3bec1;
            text-align: center;
          }
        }

        .facebook {
          background-color: #1877f2;
        }

        .telegram {
          background-color: #0088cc;
        }

        .instagram {
          background-color: #c13584;
        }

        .youtube {
          background-color: #ff0000;
        }

        .whatsapp {
          background-color: #25d366;
        }

        .x {
          background-color: #000;
        }

        .line {
          background-color: #00b900;
        }

        .tiktok {
          background-color: #000;
        }

        .gmail {
          background-color: #ea4335;
        }
      }
    }

    .support-text {
      text-align: center;
      color: #24ee89;
      margin-top: 20px;
      font-size: 14px;
      font-weight: 700;
    }
  }

  .hierarchy-chart {
    background-color: #323738;
    border-radius: 8px;

    .level-1,
    .level-2,
    .level-3 {
      display: flex;
      justify-content: center;
      gap: 20px;
    }

    .divider-line {
      height: 40px;
      border-left: 1px dashed #444;
      margin: 0 auto;
      width: 1px;
    }

    .user-node {
      width: 40px;
      height: 40px;
      border-radius: 50%;
      display: flex;
      align-items: center;
      justify-content: center;

      &.main {
        background-color: #ffc107;
      }

      &.sub {
        background-color: #4cd964;
      }

      &.sub-sub {
        background-color: #0088cc;
      }
    }

    .w-full {
      width: 100%;
    }

    .h-full {
      height: 100%;
    }
  }

  .rules-section {
    background-color: #323738;
    border-radius: 8px;
    padding: 15px;

    .rule-title {
      font-size: 18px;
      margin-bottom: 10px;
    }

    .rule-content {
      font-size: 12px;
      color: #A8AEB0;
      font-weight: 600;
      line-height: 1.6;
    }
  }

  .filter-tabs {
    background-color: #323738;
    border-radius: 8px;
    display: flex;

    .filter-tab {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 12px;
      color: #b3bec1;
      font-size: 14px;

      &.active {
        background-color: #3a4142;
        color: #fff;
      }

      i {
        margin-right: 5px;
      }
    }
  }

  .commission-table-section {
    background-color: #232626;
    border-radius: 8px;
    overflow: hidden;

    .section-title {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0px;
      border-bottom: 1px solid rgba(0, 0, 0, 0.1);

      .title-text {
        font-size: 16px;
        font-weight: 600;
      }

      .title-icon {
        width: 40px;
        height: 40px;

        img {
          width: 100%;
          height: 100%;
        }
      }
    }

    .game-tabs {
      display: flex;
      overflow-x: auto;
      padding: 8px;
      background-color: #323738;
      margin-bottom: 8px;
      border-radius: 4px;
      gap: 10px;

      .game-tab {
        padding: 8px;
        font-size: 12px;
        font-weight: 700;
        white-space: nowrap;
        color: #b3bec1;
        border-radius: 4px;

        &.active {
          background-color: #3a4142;
          color: #24ee89;
        }
      }
    }

    .level-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      gap: 3px;

      &.level-1 {
        background-color: #4cd964;
      }

      &.level-2 {
        background-color: #af52de;
      }

      &.level-3 {
        background-color: #5856d6;
      }

      &.level-4 {
        background-color: #5ac8fa;
      }

      &.level-5 {
        background-color: #ff2d55;
      }

      &.level-6 {
        background-color: #8e8e93;
      }

      &.level-7 {
        background-color: #ff9500;
      }
    }

    .price-cell {
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 12px;
      gap: 4px;
      color: #24ee89;
    }
  }
</style>
